package com.xing.service.impl;

import com.xing.dao.AccountDao;
import com.xing.dao.impl.AccountDaoImpl;
import com.xing.domain.Account;
import com.xing.service.AccountService;
import com.xing.util.DataSourceUtils;

import java.math.BigDecimal;
import java.sql.SQLException;

/*
 * 静，谦虚谨慎，心胸宽广容纳所有好的坏的、先苦后甜
 * day41_transaction
 * 2021/5/8 20:37
 */
public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao=new AccountDaoImpl();
    @Override
    public Account login(String cardNo, String pwd) {
        Account account = accountDao.select(cardNo, pwd);
        if(account==null){
            throw new RuntimeException("卡号和密码错误");
        }
        return account;
    }

    @Override
    public void transMoney(String cardNo, String toCardNo, BigDecimal money) {
        try {
            DataSourceUtils.begin();
            //1校验卡号相同
            if (cardNo.equals(toCardNo)){
                throw new RuntimeException("对方卡号不能和转出卡号相同");
            }
            //2校验对方卡号是否存在
            AccountDao accountDao=new AccountDaoImpl();
            boolean b= accountDao.select(toCardNo);
            if(!b){
                throw new RuntimeException("对方卡号不存在");
            }
            //3检验余额是否充足
            BigDecimal balance=accountDao.selectMoney(cardNo);
            if(balance.compareTo(money)<0){
                throw new RuntimeException("余额不足");
            }
            //4扣钱
            accountDao.updateTake(cardNo,money);
            //int i=10/0;

            //5存钱
            accountDao.updateSave(toCardNo,money);
            DataSourceUtils.commit();
        } catch (Exception e) {
            try {
                DataSourceUtils.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            throw new RuntimeException(e);
        } finally {
            try {
                DataSourceUtils.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
